package com.local.article.service;

import com.local.article.dao.CommentRepository;
import com.local.article.pojo.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;


    @Autowired
    private MongoTemplate mongoTemplate;

    public void saveComment(Comment comment) {
        //如果需要自定义主键，可以在这里指定。不指定则mongo会自动生成
        commentRepository.save(comment);
    }


    public void updateComment(Comment comment) {
        commentRepository.save(comment);
    }

    public void deleteCommentById(String id) {
        commentRepository.deleteById(id);
    }

    public List<Comment> findCommentList() {
        return commentRepository.findAll();
    }

    public Comment findCommentById(String id) {
        return commentRepository.findById(id).get();
    }

    public Page<Comment> findByParentid(String parentid, Integer page, Integer size) {
        //排序1：通过_id升序排列
        //return commentRepository.findByParentid(parentid, PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "_id")));

        //排序2：通过likenum降序、_id升序排列
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "likenum"));
        orders.add(new Sort.Order(Sort.Direction.ASC, "_id"));

        return commentRepository.findByParentid(parentid, PageRequest.of(page - 1, size, Sort.by(orders)));
    }


    public void updateCommentLikenum(String id) {
        //查询
        Query query = Query.query(Criteria.where("_id").is(id));
        //Query query = Query.query(Criteria.where("_id").is(id)).addCriteria(Criteria.where("state").is("0")); //多个条件用addCriteria连接

        //更新
        Update update = new Update();
        update.inc("likenum", 1);//likenum自增，每次加1。如果用-1，就是自减，每次减1

        mongoTemplate.updateFirst(query, update, Comment.class);
    }
}
